GoLang

Explain Structures in Go Programming Language | Go Programming Tutorial

Explain Structures in Go Programming Language | Go Programming Tutorial

Explain Structures in Go Programming Language | Go Programming Tutorial

In this article, you will learn:

  • What are Structures in Go Programming Language?
  • How to declare Structure?
  • How to define a Structure?

What are Structures in the Go Programming Language?

A structure or struct in GoLang is a user-defined type that groups or combines the different data type variables into a single data type. Any real-world entity which has some properties are represented as a structure. The concept of structure is compared with the classes in object-oriented programming. It can also be called a lightweight class that does not support the concept of inheritance but the concept of composition. 

Example:  Collect the information of the student: the name of the student, the class of the student, and roll_no of the student. These properties are grouped into a single type as a structure.

Declaring a structure:

Type Student_info struct{

    Name string

    Class string

    Roll_no int

}

In this above example, the type keyword is used to introduce the new type. Right the name of the structure followed by the struct keyword that is used in defining the structure. The properties defined inside the structure are name, class, and roll_no.

How to define a Structure?

var s Student_info

The above line creates a variable of the type Student_info whose default value is 0. In structure, zero means all the field's value is set to 0. 

You can initialize a variable of the structure in the following way:

var s = Student_info{“John”, “9_C”, 89}

Point to be Remembered:

  • Always pass the values of the fields in the same way they are declared in the structure. 
  • The user is not allowed to initialize some values from the complete set of values.
  • The user can initialize the subset of the fields with the help of a particular approach. i.e

var s = Student_info{Name: “John”, Roll_no: 89} // Class:””

How to access the fields of the structure?

To access specific fields of a structure, you can use the (.) dot operator.

How to use Pointers in Struct in GoLang?

Pointers are used in storing the memory address of another variable. It also allows the user to create a pointer in a struct.

Yamini  Sharma

I am working as a professional engineer in "HIghRadius Technologies Pvt. Ltd." Passionate about learning and exploring new technologies. Enthusiast in writing and sharing what I have in my knowledge bucket.